﻿using BZ.Core.Frm;
using BZ.Core.TaskExt;
using BZ.Logger;
using DevComponents.DotNetBar;
using NDK.DB;
using NDK.Module.BLL;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using static NDK.Module.Model.Common;

namespace NDK.Frm
{
    public partial class Frm_Home : Form
    {
        private static log4net.ILog opLogger = log4net.LogManager.GetLogger("OPLogger");
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("Frm_Home");
        private const int historyProgressMax = 64;
        private Func<int, DataItem, bool> updateOutputToDgv;
        private Action<Bar, bool> updateResultsProgress;
        private Action<Chart, Label, Label, Label, Label, Label> updateResultsToChart;
        private HistoryDataModel historyDataModel = new HistoryDataModel();
        private HistoryDataServices historyDataServices = new HistoryDataServices();
        private MeasureSize measureSize = new MeasureSize();
        int userWidth = Screen.PrimaryScreen.Bounds.Width;
        public double[] singleSizeYields, singleSizeNGCount, singleSizeTotals, singleSizeOKCount;
        List<string> nameList = new List<string>();
        List<MeasureSize> sizes = null;

        private static List<PictureBox> pbTryList = new List<PictureBox>();


        private Frm_Home()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static Frm_Home _instance;
        private static readonly object singletonLock = new object();
        int errCount = 0;
        public int SocketErrNum = 0;
        public static Frm_Home Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Home();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// =================HOME界面加载=======================
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Home_Load(object sender, EventArgs e)
        {
            #region 初始化饼图
            List<string> xData = new List<string>() { "NA", "NG", "OK" };
            List<int> yData = new List<int>() { 0, 1, 2 };
            chart1.Series["Series1"].Label = "#VALX:#PERCENT{P}";
            chart1.Series["Series1"].Points.DataBindXY(xData, yData);
            chart1.Series["Series1"].Points[0].Color = Color.Yellow;
            chart1.Series["Series1"].Points[1].Color = Color.Red;
            chart1.Series["Series1"].Points[2].Color = Color.Green;
            this.tb_Result.Font = new System.Drawing.Font("Microsoft YaHei", 48F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
            #endregion

            #region 绑定委托更新界面消息
            updateOutputToDgv += AddResults;
            updateResultsToChart += AddResultsToChart;
            #endregion

            #region 更新界面数据列表
            RefreshHomeUI(CurProType);
            #endregion

            #region 读取点检和上传线性文件

            PublicMethod.ReadCSVFile();

            #endregion

            #region 结果输出(dgv,chart,panel) 绑定更新界面函数
            ProcessData.UpdateUIEvent += new delegateUpdateUI(UpdataUI);
            ProcessData.UpdateNGUIEvent += new delegateUpdateNGUI(UpdataNGUI);
            #endregion

            #region 读入历史数据
            ReadHistoryData();
            #endregion
        }


        private void Instance_delegateUpdateLoadingAPLCEvent(string msg)
        {
            LoadingA.Text = msg;
            LoadingA.ForeColor = Color.Blue;
        }
        private void Instance_delegateUpdateLoadingBPLCEvent(string msg)
        {
            LoadingB.Text = msg;
            LoadingB.ForeColor = Color.Blue;
        }
        private void Instance_delegateUpdatePositionAPLCEvent(string msg)
        {
            PositionA.Text = msg;
            PositionA.ForeColor = Color.Blue;
        }
        private void Instance_delegateUpdatePositionBPLCEvent(string msg)
        {
            PositionB.Text = msg;
            PositionB.ForeColor = Color.Blue;
        }
        private void Instance_delegateUpdateUloadingPLCEvent(string msg)
        {
            Unloading.Text = msg;
            Unloading.ForeColor = Color.Blue;
        }
        public void ReadHistoryData()
        {
            try
            {
                DataTable dt1 = MySQLDBHelper.QueryNGCount1();
                singleSizeTotals = new double[ListmeasureSizeListPosition[0].Count];
                singleSizeYields = new double[ListmeasureSizeListPosition[0].Count];
                singleSizeNGCount = new double[ListmeasureSizeListPosition[0].Count];
                for (int i = 0; i < ListmeasureSizeListPosition[0].Count; i++)
                {
                    singleSizeTotals[i] = Convert.ToDouble(dt1.Rows[0][ListmeasureSizeListPosition[0][i].SizeName]);
                    singleSizeNGCount[i] = Convert.ToDouble(dt1.Rows[1][ListmeasureSizeListPosition[0][i].SizeName]);
                    singleSizeYields[i] = (singleSizeTotals[i] - singleSizeNGCount[i]) / singleSizeTotals[i];
                }

                AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
                updataUI();
            }
            catch
            {

            }
        }

        public void RefreshHomeUI(string productType)
        {
            MeasureSizeServices measureSizeService = new MeasureSizeServices();
            sizes = measureSizeService.GetAllByProjectNameAndTurnNum(productType, 1);

            if (sizes == null)
                return;

            int sizeCount = 0;
            nameList = new List<string>();
            List<DataGridViewTextBoxColumn> dgvColumns = new List<DataGridViewTextBoxColumn>();
            foreach (MeasureSize size in sizes)
            {
                if (size.IsShow)
                {
                    sizeCount++;
                    nameList.Add(size.SizeName);
                    var column = new DataGridViewTextBoxColumn()
                    {
                        FillWeight = 80,
                        ReadOnly = true,
                        Name = size.SizeName,
                        HeaderText = size.SizeName,
                        DataPropertyName = size.SizeName,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    column.HeaderCell.Style.ForeColor = size.IsJudging ? Color.Green : Color.YellowGreen;
                    dgvColumns.Add(column);
                }
            }

            //设置固定列表头
            dgv_ResultOutput.Columns.Clear();
            dgv_NGResultOutput.Columns.Clear();
            dgv_ResultOutputRote.Columns.Clear();
            string[] str = new string[5] { " ", "NGFAI", "Time", "Barcode", "Pos" };
            var FixColumn = new List<DataGridViewTextBoxColumn>();
            for (int i = 0; i < str.Length; i++)
            {
                FixColumn.Add(new DataGridViewTextBoxColumn()
                {
                    FillWeight = 80,
                    Name = str[i],
                    ReadOnly = true,
                    HeaderText = str[i],
                    DataPropertyName = str[i],
                    SortMode = DataGridViewColumnSortMode.NotSortable
                });
            }
            //良率表
            dgv_ResultOutputRote.Columns.Add((DataGridViewTextBoxColumn)FixColumn[0].Clone());
            dgvColumns.ForEach(x => dgv_ResultOutputRote.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            //NG表
            FixColumn.ForEach(x => dgv_NGResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            dgvColumns.ForEach(x => dgv_NGResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            //OK表
            FixColumn.Where(x => x.Name != str[1]).ToList().ForEach(x => dgv_ResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            dgvColumns.ForEach(x => dgv_ResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));

            AddRow(dgv_ResultOutput, 4);
            AddRow(dgv_NGResultOutput, 5);

            singleSizeYields = new double[sizeCount];
            singleSizeNGCount = new double[sizeCount];
            singleSizeTotals = new double[sizeCount];
            singleSizeOKCount = new double[sizeCount];
            dgv_ResultOutputRote.BackgroundColor = Color.Black;
            dgv_ResultOutputRote.ForeColor = Color.Green;
            dgv_ResultOutputRote.Font = new Font("隶书", 12);
            dgv_ResultOutputRote.ReadOnly = true;

            void AddRow(DataGridView dgv, int value)
            {
                try
                {
                    dgv.Rows.Clear();
                    var DgvRow = new List<DataGridViewRow>();
                    for (int i = 0; i < 3; i++)
                    {
                        DgvRow.Add(new DataGridViewRow() { ReadOnly = true });
                        DgvRow[i].CreateCells(dgv);
                    }

                    for (int index = 0; index < dgv.Columns.Count; index++)
                    {
                        if (index < value)
                        {
                            if (index == 0)
                            {
                                DgvRow[0].Cells[0].Value = "Tol(+)";
                                DgvRow[1].Cells[0].Value = "Target";
                                DgvRow[2].Cells[0].Value = "Tol(-)";
                            }
                            else
                            {
                                DgvRow.ForEach(x => x.Cells[index].Value = "-");
                            }
                        }
                        else
                        {
                            try
                            {
                                var data = sizes.SingleOrDefault(x => x.SizeName == dgv.Columns[index].HeaderText);
                                DgvRow[0].Cells[index].Value = data.UpperDeviation.ToString();
                                DgvRow[1].Cells[index].Value = data.NormValue.ToString();
                                DgvRow[2].Cells[index].Value = data.LowerDeviation.ToString();
                            }
                            catch (Exception ex)
                            {

                            }

                        }
                        DgvRow.ForEach(x => x.Cells[index].Style.ForeColor = Color.White);
                        DgvRow.ForEach(x => x.Cells[index].Style.BackColor = Color.Black);
                        DgvRow.ForEach(x => x.Cells[index].Style.Font = new Font("隶书", 12));
                    }
                    DgvRow.ForEach(x => dgv.Rows.Add(x));
                    dgv.Rows[2].Frozen = true;      //冻结前三行
                }
                catch (Exception exc)
                {
                }
            }
        }

        #region UI
        /// <summary>
        /// 显示数据栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Data_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;//防止拖拽后，导航栏消失
                    if (bar.DockSide == eDockSide.None)//防止拖拽后，未停靠到Document，就关闭tab
                    {
                        bar.DockSide = eDockSide.Document;
                    }
                    if (bar.DockSide == eDockSide.Document)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            if (dock.Name == "dockContainerItem_Data")
                            {
                                dock.Visible = true;
                                if (!bar.Visible)
                                    bar.Visible = true;
                            }
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        /// <summary>
        /// 显示所有栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_All_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;
                    if (bar.DockSide == eDockSide.None)
                    {
                        if (bar.Name == "bar_Statistics")
                        {
                            bar.DockSide = eDockSide.Left;
                        }
                        else if (bar.Name == "bar_Log")
                        {
                            bar.DockSide = eDockSide.Bottom;
                        }
                        else
                        {
                            bar.DockSide = eDockSide.Document;
                        }
                    }
                    if (bar.DockSide == eDockSide.Document
                        || bar.DockSide == eDockSide.Bottom
                        || bar.DockSide == eDockSide.Left
                        || bar.DockSide == eDockSide.Right)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            dock.Visible = true;
                            if (!bar.Visible)
                                bar.Visible = true;
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        /// <summary>
        /// 显示图像栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Image_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;
                    if (bar.DockSide == eDockSide.None)
                    {
                        bar.DockSide = eDockSide.Document;
                    }
                    if (bar.DockSide == eDockSide.Document)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            if (dock.Name == "dockContainerItem_Image")
                            {
                                dock.Visible = true;
                                if (!bar.Visible)
                                    bar.Visible = true;
                            }
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }

        /// <summary>
        /// 显示日志栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Log_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    if (bar.Name == "bar_Log")
                    {
                        bar.TabNavigation = true;
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            dock.Visible = true;
                            if (!bar.Visible)
                                bar.Visible = true;
                        }
                        break;
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        #endregion

        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x02000000;
        //        return cp;
        //    }
        //}
        #endregion

        public bool AddResults(int MeasureID, DataItem camaraData)
        {
            string SizeName = camaraData.Name;
            double MeasureValue = camaraData.Value;
            if (!nameList.Contains(camaraData.Name))
                return false;//如果尺寸不需要显示，返回false
            if (!dgv_ResultOutput.InvokeRequired)
            {
                for (int rowIndex = 0; rowIndex < dgv_ResultOutput.Rows.Count; rowIndex++)
                {
                    if (dgv_ResultOutput.Rows[rowIndex].Cells[1].Value.ToString() != camaraData.Name)
                        continue;

                    if (camaraData.JugeResult == JUDGEMENT_RESULT.NG.ToString())//NG
                    {
                        dgv_ResultOutput.Rows[rowIndex].Cells[3].Style.BackColor = Color.Red;
                    }
                    else
                    {
                        dgv_ResultOutput.Rows[rowIndex].Cells[3].Style.BackColor = Color.White;
                    }

                    dgv_ResultOutput.Rows[rowIndex].Cells[3].Value = camaraData.Value.ToString("0.0000");
                    dgv_ResultOutput.Rows[rowIndex].Cells[0].Value = MeasureID;
                    dgv_ResultOutput.Rows[rowIndex].Cells[7].Value = (camaraData.Value - double.Parse(dgv_ResultOutput.Rows[rowIndex].Cells[4].Value.ToString())).ToString("f6");
                    return true;
                }
            }
            else
            {
                this.BeginInvoke(updateOutputToDgv, new object[] { MeasureID, camaraData });
            }
            return true;

        }

        /// <summary>
        /// 更新饼图结果
        /// </summary>
        /// <param name="ret"></param>
        public void AddResultsToChart(Chart chart, Label lbl_CT, Label lbl_Total, Label OKLab, Label NGLab, Label NALab)
        {
            List<string> xData = new List<string>() { "NA", "NG", "OK" };
            //NGCount = Common.NGCount
            List<int> yData = new List<int>() { NACount, NGCount, TotalCount - NGCount - NACount };
            if (!lbl_CT.InvokeRequired)
            {
                chart.Series["Series1"].Label = "#VALX:#PERCENT{P}";

                chart.Series["Series1"].Points[0].Color = Color.Yellow;
                chart.Series["Series1"].Points[1].Color = Color.Red;
                chart.Series["Series1"].Points[2].Color = Color.Green;
                chart.Series["Series1"].Points.DataBindXY(xData, yData);

                lbl_Total.Text = "Total:" + TotalCount;
                OKLab.Text = (TotalCount - NGCount - NACount).ToString();
                NGLab.Text = NGCount.ToString();
                NALab.Text = NACount.ToString();
                //lbl_CT.Text = "CT: " + Common.TotalCT.ToString("0.000") + " S";

                double str = 100;
                if (Common.TotalCount == 0)
                {
                    str = 100.00;
                }
                else
                {
                    str = ((Common.TotalCount - Common.NGCount) / Common.TotalCount) * 100.00; //良率
                }

                //if (str < Common.RatePresentSetting) //当前良率小于设定值，则弹窗
                //{
                //    if (Common.b_DisplayNot == false)
                //    {
                //        string ss = "当前良率为：" + str.ToString("#0.00") + "%" + ", " + "小于设置的良率< " + Common.RatePresentSetting.ToString("#0.00") + "%" + " >" + "，请注意！";
                //        hint(Frm_Home.Instance, ss);
                //        Common.b_rateLow = true;
                //    }
                //    else
                //    {
                //        Common.b_rateLow = false;
                //        Dlg_Warning.Instance.Hide();
                //    }
                //}
                //else
                //{
                //    Common.b_rateLow = false;
                //    Dlg_Warning.Instance.Hide();
                //}
            }
            else
            {
                this.BeginInvoke(updateResultsToChart, new object[] { chart, lbl_CT, lbl_Total, OKLab, NGLab });
            }
        }

        private void updataUI()
        {
            for (int index = 0; index < singleSizeTotals.Length; index++)
            {
                //计算单个尺寸的良率
                if (singleSizeTotals[index] != 0)
                {
                    singleSizeYields[index] = (singleSizeTotals[index] - singleSizeNGCount[index]) / Convert.ToDouble(singleSizeTotals[index]);
                }
                else
                {
                    singleSizeYields[index] = 0;
                }

                singleSizeOKCount[index] = singleSizeTotals[index] - singleSizeNGCount[index];

            }
            List<List<string>> strings = new List<List<string>>()
                   {
                          Array.ConvertAll(singleSizeYields,x => $"{x*100:f2}%").ToList(),
                          Array.ConvertAll(singleSizeTotals,x => x.ToString()).ToList(),
                          Array.ConvertAll(singleSizeOKCount,x => x.ToString()).ToList(),
                          Array.ConvertAll(singleSizeNGCount,x => x.ToString()).ToList(),
                    };
            strings[0].Insert(0, "Yield");
            strings[1].Insert(0, "Total");
            strings[2].Insert(0, "OK");
            strings[3].Insert(0, "NG");
            dgv_ResultOutputRote.Rows.Clear();
            for (int i = 0; i < strings.Count; i++)
            {
                dgv_ResultOutputRote.Rows.Add(strings[i].ToArray());
            }
            MySQLDBHelper.UpdateNgFaiCount(ListmeasureSizeListPosition[0], singleSizeTotals, 1);
            MySQLDBHelper.UpdateNgFaiCount(ListmeasureSizeListPosition[0], singleSizeNGCount, 2);
        }

        private void Frm_Home_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
        /// <summary>
        /// 导出home界面的数据到csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_OutputToCsv_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_SaveToExcel)
            {
                if (dgv_ResultOutputRote.Rows.Count > 2)
                {
                    FileUtils.SaveNGCSV(dgv_ResultOutputRote, $"D:\\Data\\output\\data_NG");
                }
            }
        }
        /// <summary>
        /// 导出home界面的数据到csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_Log_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_Clear)
            {
                dataGridViewLogBoard1.dataGridView.Rows.Clear();
            }
        }
        /// <summary>
        /// 不断更新home页面的CT显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_CT_Tick(object sender, EventArgs e)
        {
            lbl_CT.Text = "CT:" + CtLook;
        }

        /// <summary>
        /// 更新数据到界面
        /// </summary>
        /// <param name="camaraDataList">当前测试产品的数据</param>
        private async void UpdataUI(MeasureProduct product)
        {
            List<DataItem> camaraDataList = product.MeasureData;
            if (camaraDataList == null)
                return;

            DataGridViewRow dr = new DataGridViewRow();
            try
            {
                await Task.Run(() =>
                {
                    dr.CreateCells(dgv_ResultOutput);
                    dr.Cells[1].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    dr.Cells[2].Value = product.SN;
                    dr.Cells[3].Value = product.Position;
                    for (int i = 0; i < nameList.Count + 4; i++)
                    {
                        if (i >= 4)
                        {
                            var value = camaraDataList.SingleOrDefault(x => x.Name == nameList[i - 4]);
                            if (value != null)
                            {
                                singleSizeTotals[i - 4]++;
                                dr.Cells[i].Value = value.Value.ToString("F4");
                            }
                        }
                        dr.Cells[i].Style.BackColor = Color.Black;
                        dr.Cells[i].Style.ForeColor = Color.LawnGreen;
                        dr.Cells[i].Style.Font = new Font("隶书", 12);
                    }
                });
                //新增加一行在第一行
                BeginInvoke(new Action(() =>
                {
                    updataUI();
                    if (dgv_ResultOutput.Rows.Count >= 30)
                    {
                        for (int i = 1; i <= 4; i++)
                        {
                            dgv_ResultOutput.Rows.RemoveAt(dgv_ResultOutput.Rows.Count - 1);
                        }
                    }
                    dgv_ResultOutput.Rows.Insert(3, dr);    //插入的数据作为第一行显示

                    tb_Result.Text = "OK";
                    txtBarcode.Text = product.SN;
                    tb_Result.ForeColor = Color.Green;

                    //LocalUtils.Yield.Yield.Instance.UpdateYield(true);
                    AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
                }));
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"OK数据更新界面:{ex.ToString()}", LogType.Error);
            }
        }

        /// <summary>
        /// 更新NG数据到界面
        /// </summary>
        /// <param name="camaraDataList">当前测试产品的数据</param>
        private async void UpdataNGUI(MeasureProduct product)
        {
            try
            {
                List<DataItem> camaraDataList = product.MeasureData;
                if (camaraDataList == null)
                { return; }
                DataGridViewRow dr = new DataGridViewRow();

                await Task.Run(() =>
                {
                    dr.CreateCells(dgv_NGResultOutput);

                    dr.Cells[1].Value = product.NG_FAI;
                    dr.Cells[2].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    dr.Cells[3].Value = product.SN;
                    dr.Cells[4].Value = product.Position;
                    dr.Cells[1].Style.ForeColor = Color.Red;
                    for (int i = 0; i < nameList.Count + 5; i++)
                    {
                        dr.Cells[i].Style.BackColor = Color.Black;
                        dr.Cells[i].Style.ForeColor = Color.LawnGreen;
                        dr.Cells[i].Style.Font = new Font("隶书", 12);
                        if (i >= 5)
                        {
                            var value = camaraDataList.SingleOrDefault(x => x.Name == nameList[i - 5]);
                            if (value != null)
                            {
                                singleSizeTotals[i - 5]++;
                                dr.Cells[i].Value = value.Value > 999 ? "N/A" : value.Value.ToString("F4");
                                if (value.JugeResult != JUDGEMENT_RESULT.OK.ToString())
                                {
                                    singleSizeNGCount[i - 5]++;
                                    dr.Cells[i].Style.ForeColor = Color.Red;
                                }
                            }
                        }
                    }
                });

                BeginInvoke(new Action(() =>
                {
                    updataUI();
                    if (dgv_NGResultOutput.Rows.Count >= 30)
                    {
                        for (int i = 1; i <= 4; i++)
                        {
                            dgv_NGResultOutput.Rows.RemoveAt(dgv_NGResultOutput.Rows.Count - 1);
                        }
                    }
                    if (product.Result == JUDGEMENT_RESULT.NG)
                        tb_Result.Text = "NG";
                    else
                        tb_Result.Text = "NA";
                    txtBarcode.Text = product.SN;
                    tb_Result.ForeColor = Color.Red;
                    dgv_NGResultOutput.Rows.Insert(3, dr);    //插入的数据作为第一行显示

                    //LocalUtils.Yield.Yield.Instance.UpdateYield(false);
                    AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
                }));
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"NG数据更新界面:{ex.ToString()}", LogType.Error);
            }

        }

        /// <summary>
        /// 监控窗体点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_MothionDebug)//工站步骤监控
            {
                Frm_StationDebug stationDebugFrm = Frm_StationDebug.Instance;
                stationDebugFrm.Show();
            }
            if (e.ClickedItem == tsmi_MonitorVar)//运行时变量监控
            {
                Frm_VarMonitor varMonitorFrm = new Frm_VarMonitor();
                varMonitorFrm.Show();
            }
            if (e.ClickedItem == tsmi_MonitorTask)//线程状态监控
            {
                Frm_TaskMonitor taskMonitorForm = new Frm_TaskMonitor();
                taskMonitorForm.Show();
            }
        }

        /// <summary>
        /// Chart图表 清空重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_DoubleClick(object sender, EventArgs e)
        {
            FileUtils.ClearFile(INIUtils.Path);
            Common.NGCount = 0;
            Common.TotalCount = 0;
            Common.NACount = 0;
            Common.ExceptionCount = 0;

            for (int i = 0; i < singleSizeTotals.Length; i++)
            {
                singleSizeTotals[i] = 0;
                singleSizeYields[i] = 0;
                singleSizeNGCount[i] = 0;
            }

            AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);

            dgv_ResultOutput.Rows.Clear();
            dgv_NGResultOutput.Rows.Clear();
            dgv_ResultOutputRote.Rows.Clear();

            #region 建立OK UI尺寸上下限固定行
            dgv_ResultOutput.Rows.Clear();
            try
            {
                DataGridViewRow drUpper = new DataGridViewRow();
                DataGridViewRow drNorma = new DataGridViewRow();
                DataGridViewRow drLower = new DataGridViewRow();
                drUpper.CreateCells(dgv_ResultOutput);
                drNorma.CreateCells(dgv_ResultOutput);
                drLower.CreateCells(dgv_ResultOutput);
                drUpper.ReadOnly = true;
                drNorma.ReadOnly = true;
                drLower.ReadOnly = true;

                //USL前端
                drUpper.Cells[0].Value = "Tol(+)";
                drUpper.Cells[1].Value = "-";
                drUpper.Cells[2].Value = "-";
                drUpper.Cells[3].Value = "-";

                drUpper.Cells[0].Style.BackColor = Color.Black;
                drUpper.Cells[1].Style.BackColor = Color.Black;
                drUpper.Cells[2].Style.BackColor = Color.Black;
                drUpper.Cells[3].Style.BackColor = Color.Black;

                drUpper.Cells[0].Style.ForeColor = Color.White;
                drUpper.Cells[1].Style.ForeColor = Color.White;
                drUpper.Cells[2].Style.ForeColor = Color.White;
                drUpper.Cells[3].Style.ForeColor = Color.White;

                drUpper.Cells[0].Style.Font = new Font("隶书", 12);
                drUpper.Cells[1].Style.Font = new Font("隶书", 12);
                drUpper.Cells[2].Style.Font = new Font("隶书", 12);
                drUpper.Cells[3].Style.Font = new Font("隶书", 12);

                //Nom前端
                drNorma.Cells[0].Value = "Target";
                drNorma.Cells[1].Value = "-";
                drNorma.Cells[2].Value = "-";
                drNorma.Cells[3].Value = "-";

                drNorma.Cells[0].Style.BackColor = Color.Black;
                drNorma.Cells[1].Style.BackColor = Color.Black;
                drNorma.Cells[2].Style.BackColor = Color.Black;
                drNorma.Cells[3].Style.BackColor = Color.Black;

                drNorma.Cells[0].Style.ForeColor = Color.White;
                drNorma.Cells[1].Style.ForeColor = Color.White;
                drNorma.Cells[2].Style.ForeColor = Color.White;
                drNorma.Cells[3].Style.ForeColor = Color.White;

                drNorma.Cells[0].Style.Font = new Font("隶书", 12);
                drNorma.Cells[1].Style.Font = new Font("隶书", 12);
                drNorma.Cells[2].Style.Font = new Font("隶书", 12);
                drNorma.Cells[3].Style.Font = new Font("隶书", 12);

                //LSL前端
                drLower.Cells[0].Value = "Tol(-)";
                drLower.Cells[1].Value = "-";
                drLower.Cells[2].Value = "-";
                drLower.Cells[3].Value = "-";

                drLower.Cells[0].Style.BackColor = Color.Black;
                drLower.Cells[1].Style.BackColor = Color.Black;
                drLower.Cells[2].Style.BackColor = Color.Black;
                drLower.Cells[3].Style.BackColor = Color.Black;

                drLower.Cells[0].Style.ForeColor = Color.White;
                drLower.Cells[1].Style.ForeColor = Color.White;
                drLower.Cells[2].Style.ForeColor = Color.White;
                drLower.Cells[3].Style.ForeColor = Color.White;

                drLower.Cells[0].Style.Font = new Font("隶书", 12);
                drLower.Cells[1].Style.Font = new Font("隶书", 12);
                drLower.Cells[2].Style.Font = new Font("隶书", 12);
                drLower.Cells[3].Style.Font = new Font("隶书", 12);


                //判定每个尺寸
                for (int index = 0; index < dgv_ResultOutput.Columns.Count - 4; index++)
                {
                    //string[] str_FAI = dgv_ResultOutput.Columns[index + 4].HeaderText.Split(',', '\n', '(', '|', ')')
                    //获得上限、理论值、下限
                    for (int jj = 0; jj < sizes.Count; jj++)
                    {
                        if (sizes[jj].SizeName == dgv_ResultOutput.Columns[index + 4].HeaderText)
                        {
                            drUpper.Cells[index + 4].Value = sizes[jj].UpperDeviation.ToString();//"0.000"
                            drNorma.Cells[index + 4].Value = sizes[jj].NormValue.ToString();
                            drLower.Cells[index + 4].Value = sizes[jj].LowerDeviation.ToString();

                            drUpper.Cells[index + 4].Style.BackColor = Color.Black;
                            drNorma.Cells[index + 4].Style.BackColor = Color.Black;
                            drLower.Cells[index + 4].Style.BackColor = Color.Black;

                            drUpper.Cells[index + 4].Style.ForeColor = Color.White;
                            drNorma.Cells[index + 4].Style.ForeColor = Color.White;
                            drLower.Cells[index + 4].Style.ForeColor = Color.White;

                            drUpper.Cells[index + 4].Style.Font = new Font("隶书", 12);
                            drNorma.Cells[index + 4].Style.Font = new Font("隶书", 12);
                            drLower.Cells[index + 4].Style.Font = new Font("隶书", 12);
                        }
                    }
                }
                dgv_ResultOutput.Rows.Insert(0, drLower);    //插入的数据作为第一行显示
                dgv_ResultOutput.Rows.Insert(0, drNorma);    //插入的数据作为第二行显示
                dgv_ResultOutput.Rows.Insert(0, drUpper);    //插入的数据作为第三行显示
                dgv_ResultOutput.Rows[2].Frozen = true;      //冻结前三行
            }
            catch (Exception exc)
            {
            }
            #endregion

            #region 建立NG UI尺寸上下限固定行
            dgv_NGResultOutput.Rows.Clear();
            try
            {
                DataGridViewRow drUpper = new DataGridViewRow();
                DataGridViewRow drNorma = new DataGridViewRow();
                DataGridViewRow drLower = new DataGridViewRow();
                drUpper.CreateCells(dgv_NGResultOutput);
                drNorma.CreateCells(dgv_NGResultOutput);
                drLower.CreateCells(dgv_NGResultOutput);
                drUpper.ReadOnly = true;
                drNorma.ReadOnly = true;
                drLower.ReadOnly = true;

                //USL前端
                drUpper.Cells[0].Value = "Tol(+)";
                drUpper.Cells[1].Value = "-";
                drUpper.Cells[2].Value = "-";
                drUpper.Cells[3].Value = "-";
                drUpper.Cells[4].Value = "-";

                drUpper.Cells[0].Style.BackColor = Color.Black;
                drUpper.Cells[1].Style.BackColor = Color.Black;
                drUpper.Cells[2].Style.BackColor = Color.Black;
                drUpper.Cells[3].Style.BackColor = Color.Black;
                drUpper.Cells[4].Style.BackColor = Color.Black;

                drUpper.Cells[0].Style.ForeColor = Color.White;
                drUpper.Cells[1].Style.ForeColor = Color.White;
                drUpper.Cells[2].Style.ForeColor = Color.White;
                drUpper.Cells[3].Style.ForeColor = Color.White;
                drUpper.Cells[4].Style.ForeColor = Color.White;

                drUpper.Cells[0].Style.Font = new Font("隶书", 12);
                drUpper.Cells[1].Style.Font = new Font("隶书", 12);
                drUpper.Cells[2].Style.Font = new Font("隶书", 12);
                drUpper.Cells[3].Style.Font = new Font("隶书", 12);
                drUpper.Cells[4].Style.Font = new Font("隶书", 12);

                //Nom前端
                drNorma.Cells[0].Value = "Target";
                drNorma.Cells[1].Value = "-";
                drNorma.Cells[2].Value = "-";
                drNorma.Cells[3].Value = "-";
                drNorma.Cells[4].Value = "-";

                drNorma.Cells[0].Style.BackColor = Color.Black;
                drNorma.Cells[1].Style.BackColor = Color.Black;
                drNorma.Cells[2].Style.BackColor = Color.Black;
                drNorma.Cells[3].Style.BackColor = Color.Black;
                drNorma.Cells[4].Style.BackColor = Color.Black;

                drNorma.Cells[0].Style.ForeColor = Color.White;
                drNorma.Cells[1].Style.ForeColor = Color.White;
                drNorma.Cells[2].Style.ForeColor = Color.White;
                drNorma.Cells[3].Style.ForeColor = Color.White;
                drNorma.Cells[4].Style.ForeColor = Color.White;

                drNorma.Cells[0].Style.Font = new Font("隶书", 12);
                drNorma.Cells[1].Style.Font = new Font("隶书", 12);
                drNorma.Cells[2].Style.Font = new Font("隶书", 12);
                drNorma.Cells[3].Style.Font = new Font("隶书", 12);
                drNorma.Cells[4].Style.Font = new Font("隶书", 12);

                //LSL前端
                drLower.Cells[0].Value = "Tol(-)";
                drLower.Cells[1].Value = "-";
                drLower.Cells[2].Value = "-";
                drLower.Cells[3].Value = "-";
                drLower.Cells[4].Value = "-";

                drLower.Cells[0].Style.BackColor = Color.Black;
                drLower.Cells[1].Style.BackColor = Color.Black;
                drLower.Cells[2].Style.BackColor = Color.Black;
                drLower.Cells[3].Style.BackColor = Color.Black;
                drLower.Cells[4].Style.BackColor = Color.Black;

                drLower.Cells[0].Style.ForeColor = Color.White;
                drLower.Cells[1].Style.ForeColor = Color.White;
                drLower.Cells[2].Style.ForeColor = Color.White;
                drLower.Cells[3].Style.ForeColor = Color.White;
                drLower.Cells[4].Style.ForeColor = Color.White;

                drLower.Cells[0].Style.Font = new Font("隶书", 12);
                drLower.Cells[1].Style.Font = new Font("隶书", 12);
                drLower.Cells[2].Style.Font = new Font("隶书", 12);
                drLower.Cells[3].Style.Font = new Font("隶书", 12);
                drLower.Cells[4].Style.Font = new Font("隶书", 12);


                //判定每个尺寸
                for (int index = 0; index < dgv_NGResultOutput.Columns.Count - 5; index++)
                {
                    //string[] str_FAI = dgv_ResultOutput.Columns[index + 4].HeaderText.Split(',', '\n', '(', '|', ')')
                    //获得上限、理论值、下限
                    for (int jj = 0; jj < sizes.Count; jj++)
                    {
                        if (sizes[jj].SizeName == dgv_NGResultOutput.Columns[index + 5].HeaderText)
                        {
                            drUpper.Cells[index + 5].Value = sizes[jj].UpperDeviation.ToString();
                            drNorma.Cells[index + 5].Value = sizes[jj].NormValue.ToString();
                            drLower.Cells[index + 5].Value = sizes[jj].LowerDeviation.ToString();

                            drUpper.Cells[index + 5].Style.BackColor = Color.Black;
                            drNorma.Cells[index + 5].Style.BackColor = Color.Black;
                            drLower.Cells[index + 5].Style.BackColor = Color.Black;

                            drUpper.Cells[index + 5].Style.ForeColor = Color.White;
                            drNorma.Cells[index + 5].Style.ForeColor = Color.White;
                            drLower.Cells[index + 5].Style.ForeColor = Color.White;

                            drUpper.Cells[index + 5].Style.Font = new Font("隶书", 12);
                            drNorma.Cells[index + 5].Style.Font = new Font("隶书", 12);
                            drLower.Cells[index + 5].Style.Font = new Font("隶书", 12);
                        }
                    }
                }
                dgv_NGResultOutput.Rows.Insert(0, drLower);    //插入的数据作为第一行显示
                dgv_NGResultOutput.Rows.Insert(0, drNorma);    //插入的数据作为第二行显示
                dgv_NGResultOutput.Rows.Insert(0, drUpper);    //插入的数据作为第三行显示
                dgv_NGResultOutput.Rows[2].Frozen = true;      //冻结前三行
            }
            catch (Exception exc)
            {
            }
            #endregion

            #region 初始化显示良率表的行头
            string[] RowName = new string[4];

            RowName[0] = "Yield";
            dgv_ResultOutputRote.ReadOnly = true;
            dgv_ResultOutputRote.BackgroundColor = Color.Black;
            dgv_ResultOutputRote.ForeColor = Color.Green;
            dgv_ResultOutputRote.Rows.Add(RowName);
            RowName[0] = "Total";
            dgv_ResultOutputRote.Rows.Add(RowName);
            RowName[0] = "OK";
            dgv_ResultOutputRote.Rows.Add(RowName);
            RowName[0] = "NG";
            dgv_ResultOutputRote.Rows.Add(RowName);

            dgv_ResultOutputRote.Rows[0].DefaultCellStyle.BackColor = Color.Black;
            dgv_ResultOutputRote.Rows[1].DefaultCellStyle.BackColor = Color.Black;
            dgv_ResultOutputRote.Rows[2].DefaultCellStyle.BackColor = Color.Black;
            dgv_ResultOutputRote.Rows[3].DefaultCellStyle.BackColor = Color.Black;

            dgv_ResultOutputRote.Rows[0].Cells[0].Style.ForeColor = Color.Green;
            dgv_ResultOutputRote.Rows[1].Cells[0].Style.ForeColor = Color.Green;
            dgv_ResultOutputRote.Rows[2].Cells[0].Style.ForeColor = Color.Green;
            dgv_ResultOutputRote.Rows[3].Cells[0].Style.ForeColor = Color.Green;
            #endregion

            if (singleSizeTotals != null)
            {
                for (int i = 0; i < singleSizeTotals.Count(); i++)
                {
                    singleSizeTotals[i] = 0;
                    singleSizeNGCount[i] = 0;
                    singleSizeYields[i] = 0;
                }
                MySQLDBHelper.UpdateNgFaiCount(ListmeasureSizeListPosition[0], singleSizeTotals, 1);
                MySQLDBHelper.UpdateNgFaiCount(ListmeasureSizeListPosition[0], singleSizeNGCount, 2);
                updataUI();
            }
        }

        #region 数据显示
        private void InitDgvResultList()
        {
            DataGridView dgvResult = dgv_ResultOutput;
            dgvResult.AutoGenerateColumns = false;
            dgvResult.Columns.Clear();
            StringBuilder rowString = new StringBuilder();

            DataGridViewLinkColumn col = new DataGridViewLinkColumn();
            col.DataPropertyName = "SN";
            col.HeaderText = "SN";
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgvResult.Columns.Add(col);

            DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
            col2.DataPropertyName = "Color";
            col2.HeaderText = "Color";
            dgvResult.Columns.Add(col2);

            col2 = new DataGridViewTextBoxColumn();
            col2.DataPropertyName = "ProRes";
            col2.HeaderText = "ProRes";
            dgvResult.Columns.Add(col2);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResLogo";
            col.HeaderText = "Logo";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResFcam";
            col.HeaderText = "Fcam";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResRcam";
            col.HeaderText = "Rcam";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResTrim";
            col.HeaderText = "Trim";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResPlateau";
            col.HeaderText = "Plateau";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResBG";
            col.HeaderText = "BG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResBRT";
            col.HeaderText = "BRT";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResCG";
            col.HeaderText = "CG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResCRT";
            col.HeaderText = "CRT";
            dgvResult.Columns.Add(col);

            //////////////////////////////////////////
            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResBGColor";
            col.HeaderText = "BGColor";
            dgvResult.Columns.Add(col);

            //col = new DataGridViewLinkColumn();
            //col.DataPropertyName = "ResBGRT";
            //col.HeaderText = "BGRT";
            //dgvResult.Columns.Add(col);

            //col = new DataGridViewLinkColumn();
            //col.DataPropertyName = "ResCGRT";
            //col.HeaderText = "CGRT";
            //dgvResult.Columns.Add(col);
            ////////////////////////////////////////////////

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "HB_CG";
            col.HeaderText = "HB_CG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VUVD_CG";
            col.HeaderText = "VUVD_CG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "HB";
            col.HeaderText = "HB";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VUVD_BG";
            col.HeaderText = "VUVD_BG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "HB_BG";
            col.HeaderText = "HB_BG";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VUVD";
            col.HeaderText = "VUVD";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "RB_U";
            col.HeaderText = "RB_U";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VU_U";
            col.HeaderText = "VU_U";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VD_U";
            col.HeaderText = "VD_U";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "HB_U";
            col.HeaderText = "HB_U";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "HB_D";
            col.HeaderText = "HB_D";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "RB_D";
            col.HeaderText = "RB_D";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VU_D";
            col.HeaderText = "VU_D";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "VD_D";
            col.HeaderText = "VD_D";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Left_1";
            col.HeaderText = "Band_Left_1";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Right_2";
            col.HeaderText = "Band_Right_2";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Right_1";
            col.HeaderText = "Band_Right_1";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Left_2";
            col.HeaderText = "Band_Left_2";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Top";
            col.HeaderText = "Band_Top";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Bottom";
            col.HeaderText = "Band_Bottom";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Corner_3";
            col.HeaderText = "Band_Corner_3";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Corner_2";
            col.HeaderText = "Band_Corner_2";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Corner_1";
            col.HeaderText = "Band_Corner_1";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "Band_Corner_4";
            col.HeaderText = "Band_Corner_4";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResBand1";
            col.HeaderText = "Band1";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResMesh";
            col.HeaderText = "Mesh";
            dgvResult.Columns.Add(col);

            col = new DataGridViewLinkColumn();
            col.DataPropertyName = "ResBand2";
            col.HeaderText = "Band2";
            dgvResult.Columns.Add(col);

            col2 = new DataGridViewTextBoxColumn();
            col2.DataPropertyName = "InputTime";
            col2.HeaderText = "InputTime";
            dgvResult.Columns.Add(col2);
            col2.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            col2 = new DataGridViewTextBoxColumn();
            col2.DataPropertyName = "OutputTime";
            col2.HeaderText = "OutputTime";
            dgvResult.Columns.Add(col2);
            col2.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

            //col = new DataGridViewLinkColumn();
            //col.DataPropertyName = "ID";
            //col.HeaderText = "ID";
            //col.Visible = false;
            //dgvResult.Columns.Add(col);

        }

        private void tb_ext_TextChanged(object sender, EventArgs e)
        {
            saveCSVpathName = tb_ext.Text.Trim();
            if (saveCSVpathName.Contains(" "))
                saveCSVpathName = saveCSVpathName.Replace(" ", "_");
        }

        private void dgv_NGResultOutput_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                e.Cancel = true;
            }
            catch (Exception)
            {

            }
        }

        private void dgv_ResultOutputRote_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                e.Cancel = true;
            }
            catch (Exception)
            {

            }
        }

        private void dgv_ResultOutput_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                e.Cancel = true;
            }
            catch (Exception)
            {

            }
        }

        private void tb_ext_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                e.SuppressKeyPress = true;
        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        #endregion

        private static void WriteLogToTxt(string strLog, string Path)
        {

            String System_Now_Time = null;
            String File_Create_Time = null;

            System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
            File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
            string logDocument = File_Create_Time + ".txt";

            string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "//" + Path;//VisionSendMessage";
            if (!Directory.Exists(logFilePath))
            {
                Directory.CreateDirectory(logFilePath);
            }
            logFilePath = logFilePath + "//" + logDocument;
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(System_Now_Time + ":   " + strLog);
            sw.Flush();
            sw.Close();
            fs.Close();

        }

    }
}

